package com.ruoyi.house.service.impl;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.BaseEntity;
import org.apache.shiro.SecurityUtils;
import com.ruoyi.house.dto.SysUserInfo;
import com.ruoyi.house.enums.UserType;
import com.ruoyi.house.service.BaseService;
import com.ruoyi.house.utils.SpringUtils;
import com.ruoyi.house.utils.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

public abstract class BaseServiceImpl<M extends BaseMapper<E>, E extends BaseEntity>
		extends ServiceImpl<M, E> implements BaseService<E> {
	
	protected Logger logger = LoggerFactory.getLogger(this.getClass());
	
	private DataSourceTransactionManager transactionMgr;
	protected DataSourceTransactionManager getTransactionMgr() {
		if (transactionMgr == null) {
			transactionMgr = SpringUtils.getBean(DataSourceTransactionManager.class);
		}
		return transactionMgr;
	}
	
	protected TransactionStatus beginTransaction() {
		return beginTransaction(TransactionDefinition.PROPAGATION_REQUIRED);
	}

	protected TransactionStatus beginTransaction(int propagationBehavior) {
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(propagationBehavior);
		return getTransactionMgr().getTransaction(def);
	}
	
	protected void commit(TransactionStatus status) {
		getTransactionMgr().commit(status);
	}
	
	protected void rollback(TransactionStatus status) {
		getTransactionMgr().rollback(status);
	}

	protected long getLoginUserid() {
		long loginUserId = 0l; // 没有登录用户的时候，比如定时处理过来的，默认用0
		UserType loginUserType = WebUtils.getUserType();
		if (loginUserType == UserType.B_USER) {
			SysUserInfo user = (SysUserInfo)SecurityUtils.getSubject().getPrincipal();
			if (user != null) {
				loginUserId = user.getUserId();
			}
		}
		else if (loginUserType == UserType.C_USER) {
			String userId = (String)RequestContextHolder.getRequestAttributes().getAttribute("LOGIN_USER_KEY", RequestAttributes.SCOPE_REQUEST);
			if (StringUtils.isNotBlank(userId)) {
				loginUserId = Long.valueOf(userId);
			}
		}
		return loginUserId;
	}	
	
	
}
